<template>
    <el-card>
        <!-- 卡片顶部按钮 -->
        <el-button type="primary" size="default" icon="Plus" @click="addTrademark">添加品牌</el-button>
        <!-- 表格组件 -->
        <el-table style="margin: 10px 0px;" border :data="trademarkArr">
            <el-table-column label="序号" align="center" width="180px" type="index"></el-table-column>
            <el-table-column label="品牌名称" prop="tmName"></el-table-column>
            <el-table-column label="品牌logo">
                <template #="{ row }">
                    <img :src="row.logoUrl" alt="" style="width: 100px; height: 100px;">
                </template>
            </el-table-column>
            <el-table-column label="品牌操作">
                <template #="{ row }">
                    <el-button type="primary" size="small" icon="Edit" @click="updateTrademark(row)"></el-button>
                    <el-popconfirm :title="`您确定要删除${row.tmName}?`" width="250px" icon="Delete"
                        @confirm='removeTradeMark(row.id)'>
                        <template #reference>
                            <el-button type="primary" size="small" icon="Delete"></el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!-- 展示分页器组件 -->
        <!-- 分页器组件
                pagination
                   v-model:current-page:设置分页器当前页码
                   v-model:page-size:设置每一个展示数据条数
                   page-sizes:用于设置下拉菜单数据
                   background:设置分页器按钮的背景颜色
                   layout:可以设置分页器六个子组件布局调整
            -->
        <el-pagination @current-change="getHasTrademark" @size-change="sizeChange" v-model:current-page="pageNo"
            v-model:page-size="limit" :page-sizes="[3, 5, 7, 9]" :background="true"
            layout=" prev, pager, next, jumper,->,sizes,total" :total="total" />


        <!-- 修改表格数据和添加表格数据的对话框组件 -->
        <el-dialog v-model="dialogFormVisible" :title="trademarkParams.id ? '修改品牌' : '添加品牌'" width="500" align-center
            center>
            <el-form v-model="trademarkParams" :model="trademarkParams" :rules="rules" ref="formRef">
                <el-form-item label="品牌名称" label-width="100px" prop="tmName">
                    <el-input placeholder="请您输入品牌名称" v-model="trademarkParams.tmName"></el-input>
                </el-form-item>
                <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
                    <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload" :show-file-list="false"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="trademarkParams.logoUrl" :src="trademarkParams.logoUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="cancle">取消</el-button>
                    <el-button type="primary" @click="confirm">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </el-card>
</template>

<script setup lang="ts">
import { ElMessage, UploadProps } from 'element-plus'
import { ref, onMounted, reactive, nextTick } from 'vue';
import type { Records, TradeMarkResponseData, TradeMark } from '@/api/product/trademark/type';
//当前页码
let pageNo = ref<number>(1);
//每一页展示多少条数据
let limit = ref<number>(3);

// 获取总共的页数
let total = ref<number>(0);
// 定义品牌列表数组
let trademarkArr = ref<Records>([]);
// 控制对话框的显示与隐藏
let dialogFormVisible = ref<boolean>(false);

//定义收集新增品牌数据
let trademarkParams = reactive<TradeMark>({
    tmName: '',
    logoUrl: ''
})
// 获取表单组件实例
const formRef = ref()
import { reqHasTrademark, reqAddOrUpdateTradeMark, reqDeleteTradeMark } from "@/api/product/trademark"
// 将接口封装为一个函数，需要时调用函数即可
const getHasTrademark = async (pager = 1) => {
    pageNo.value = pager
    let result: TradeMarkResponseData = await reqHasTrademark(pageNo.value, limit.value);
    if (result.code == 200) {
        total.value = result.data.total;
        trademarkArr.value = result.data.records;
    }
}
// 组件挂载完毕，先获取一下数据
onMounted(() => {
    getHasTrademark()
})

// 下拉菜单页码发生变化时的回调函数
const sizeChange = () => {
    getHasTrademark()
}

// 添加品牌的回调

const addTrademark = () => {
    dialogFormVisible.value = true;
    // 将存在在数据都清空，防止数据除出错
    trademarkParams.tmName = '';
    trademarkParams.logoUrl = '';
    trademarkParams.id = 0;

    // 将表单校验规则清空
    nextTick(() => {
        // 将所有规则清空
        formRef.value.clearValidate();
    })



}
// 修改品牌的回调
const updateTrademark = (row: TradeMark) => {

    dialogFormVisible.value = true;
    // 将数据显示在对话框中
    //ES6语法合并对象
    Object.assign(trademarkParams, row);
    // 将表单校验规则清空
    nextTick(() => {
        formRef.value.clearValidate();
    })
}

//上传图片组件->上传图片之前触发的钩子函数
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    //钩子是在图片上传成功之前触发,上传文件之前可以约束文件类型与大小
    //要求:上传文件格式png|jpg|gif 4M
    if (rawFile.type == 'image/png' || rawFile.type == 'image/jpeg' || rawFile.type == 'image/gif') {
        if (rawFile.size / 1024 / 1024 < 4) {
            return true;
        } else {
            ElMessage({
                type: 'error',
                message: '上传文件大小小于4M'
            })
            return false;
        }
    } else {
        ElMessage({
            type: 'error',
            message: "上传文件格式务必PNG|JPG|GIF"
        })
        return false;
    }
}
//图片上传成功钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
    //response:即为当前这次上传图片post请求服务器返回的数据
    //收集上传图片的地址,添加一个新的品牌的时候带给服务器

    trademarkParams.logoUrl = response.data;
    // logo上传成功之后，应该将表单校验规则清空
    formRef.value.clearValidate();
}

// 点击取消按钮的回调
const cancle = () => {
    dialogFormVisible.value = false;

}

// 点击确定按钮的回调
const confirm = async () => {
    // 在点击确定按钮之后，应对表单进行校验，校验通过之后，在发送网络请求
    await formRef.value.validate();
    let result: any = await reqAddOrUpdateTradeMark(trademarkParams)
    if (result.code == 200) {
        ElMessage({
            type: "success",
            message: trademarkParams.id ? '修改品牌成功' : '添加品牌成功'
        })
        //添加成功后关闭对话框
        dialogFormVisible.value = false;
        //重新获取品牌列表 刷新列表
        getHasTrademark(trademarkParams.id ? pageNo.value : 1)
    } else {
        ElMessage({
            type: "error",
            message: trademarkParams.id ? '修改品牌失败' : '添加品牌失败'
        })
        //关闭对话框
        dialogFormVisible.value = false;
    }

}

// 品牌自定义校验规则
const validatorTmName = (_rule: any, value: any, callback: any) => {
    if (value.trim().length > 2) {
        callback()
    } else {
        callback(new Error('品牌名称不能小于2位'))
    }
}
// 品牌logo自定义校验规则
const validatorLogoUrl = (_rule: any, value: any, callback: any) => {
    //如果图片上传
    if (value) {
        callback();
    } else {
        callback(new Error('LOGO图片不能为空'))
    }
}


// 校验规则的判定
const rules = {
    tmName: [
        { required: true, trigger: 'blur', validator: validatorTmName }
    ],
    logoUrl: [{ required: true, validator: validatorLogoUrl }]
}

// 删除品牌的回调函数
const removeTradeMark = async (id: number) => {
    let result = await reqDeleteTradeMark(id);
    if (result.code == 200) {
        ElMessage({
            type: 'success',
            message: '删除品牌成功'
        })
        //重新获取品牌列表 刷新列表
        // 当当前页的数据被删除完毕后，应该返回到上一页
        let flag = trademarkArr.value.length > 1 ? pageNo.value : pageNo.value - 1
        getHasTrademark(flag)
    } else {
        ElMessage({
            type: 'error',
            message: '删除品牌失败'
        })
    }
}





</script>
<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>